#coding=utf-8
# get 流通A股数量 from sina
import stutils
from decimal import Decimal

def get_ts_from_table(table):
    #change_date; pulish_date, 变动原因, 总股本, 流通A股,限售A股
    data = []
    cs = table.contents
    
    d = []
    for td in cs[1].contents[1:]:
        date = td.string
        d.append(date.encode('u8'))
    data.append(d)
  
    d = []
    for td in cs[7].contents[1:]:
        d.append(td.string)
    d = [i[:-2].encode('u8') for i in d if i]
    d = [  str( int (Decimal(i) * 10000) )  for i in d]
    data.append(d)
    
    data = zip(*data)        
    
    result = []
    for d in data:
        if d[-1] == '0':continue
        result.append(list(d))
    
    return result

def get_ts_from_soup(soup):
    #print soup
    data = []
    t = unicode('变动日期', 'u8')
    bds = soup.findAll(text= lambda(x): x.find( t )!=-1)
    #print len(bds)
    
    #i = 0
    for bd in bds:
        #i = i + 1
        table = bd.parent.parent.parent
        #print i
        d = get_ts_from_table(table)
        data.extend(d)
        
    return data

def get_ts(code):

    url = 'http://money.finance.sina.com.cn/corp/go.php/vCI_StockStructure/stockid/%s.phtml'%code
    s = stutils.get_soup(url)
    data = get_ts_from_soup(s)
    
    return data

if  __name__ == '__main__':
    codes = stutils.all_stcodes()
    data = []
